package com.siruier.boss.ui.helper

import android.content.Intent
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.siruier.boss.BuildConfig
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.loginApi
import com.siruier.boss.common.ACTION_REQUEST
import com.siruier.boss.ui.activity.commom.openSystemUrl
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.utils.Logger
import com.xuexiang.xupdate.easy.EasyUpdate
import com.xuexiang.xupdate.entity.DownloadEntity
import com.xuexiang.xupdate.entity.UpdateEntity
import com.xuexiang.xupdate.utils.UpdateUtils

object AppUpdateHelper : DefaultLifecycleObserver, Receiver {

    private const val CHECK_UPDATE_INTERVAL = 60 * 60 * 1000
    private var activity: FragmentActivity? = null
    private var lastCheckUpdateTime: Long = System.currentTimeMillis()
    private var isCheckUpdate = false

    fun FragmentActivity.initUpdate() {
        if (activity != null) {
            return
        }
        activity = this
        lifecycle.addObserver(AppUpdateHelper)
        localRegisterReceiver(ACTION_REQUEST, AppUpdateHelper)
        checkUpdate()
    }

    fun checkUpdate(forceCheck: Boolean = false, callback: ((Boolean) -> Unit)? = null) {
        // 超过一个小时从新检查一次
        if (forceCheck || (isCheckUpdate && System.currentTimeMillis() - lastCheckUpdateTime > CHECK_UPDATE_INTERVAL)) {
            isCheckUpdate = false
        }
        if (!isCheckUpdate) {
            isCheckUpdate = true
            activity?.launchUI({
                val appConfig = loginApi.version(BuildConfig.VERSION_NAME)
                if (appConfig.isOk && appConfig.data != null && isUpdate(BuildConfig.VERSION_NAME, appConfig.data!!.version)) {
                    val version = appConfig.data!!
                    if (version.url.endsWith(".apk")) {
                        val updateEntity = UpdateEntity().apply {
                            isHasUpdate = true
                            isForce = version.isForce == 1
                            setIsIgnorable(false)
                            versionCode = BuildConfig.VERSION_CODE
                            versionName = version.version
                            updateContent = "有新版本"
                            downLoadEntity = DownloadEntity()
                                .setCacheDir(UpdateUtils.getDefaultDiskCacheDirPath())
                                .setDownloadUrl(version.url)
                            setIsSilent(false)
                            setIsAutoInstall(true)
                        }
                        EasyUpdate.checkUpdate(activity!!, updateEntity)
                    } else {
                        activity?.showAlertDialog {
                            message(message = "有新版本，下载新版本")
                            mCancelable = version.isForce != 1
                            showClose = mCancelable
                            if (mCancelable) {
                                negativeButton { }
                            }
                            positiveButton(name = "去更新") {
                                activity?.openSystemUrl(version.url)
                            }
                        }
                    }
                    callback?.invoke(true)
                } else {
                    callback?.invoke(false)
                }
                lastCheckUpdateTime = System.currentTimeMillis()
            }, error = {
                Logger.e(it)
                callback?.invoke(false)
                isCheckUpdate = false
            })
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        owner.lifecycle.removeObserver(AppUpdateHelper)
        activity = null
    }

    override fun invoke(intent: Intent) {
        checkUpdate()
    }

    private fun isUpdate(versionName: String, serviceVersion: String): Boolean {
        Logger.e("versionName==<${versionName}<===>${serviceVersion}")
        var isUpdate = false
        try {
            val versionNameArr = versionName.split(".").toTypedArray()
            val serviceVersionArr = serviceVersion.split(".").toTypedArray()
            // 本地小于服务器更新1.0  1.1
            for (i in 0 until Math.min(versionNameArr.size, serviceVersionArr.size)) {
                val local = versionNameArr[i].toInt()
                val service = serviceVersionArr[i].toInt()
                if (local < service) {
                    isUpdate = true
                    break
                } else if (local == service) { // 跳过
                } else { // 本地大于远端，不更新
                    break
                }
            }
            if (!isUpdate && versionNameArr.size < serviceVersionArr.size) {
                isUpdate = true
            }
        } catch (e: Exception) {
            Logger.e(e)
        }
        return isUpdate
    }
}

